﻿using BaseAuthRole.Domain.Input;
using BaseAuthRole.Domain.OutPut;
using BaseAuthRole.IService;
using BaseAuthRole.Web.Filters;
using Lutos.Dictionary.SDK.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using RS.BaseModel.Common;

namespace BaseAuthRole.Web.Api.Client
{
    /// <summary>
    /// 项目成员
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProjectUserForClientController : ControllerBase
    {
        private IUserService _userService;
        private ILtDictionaryClient _ltDictionaryClient;

        public ProjectUserForClientController(IUserService userService, ILtDictionaryClient ltDictionaryClient)
        {
            this._userService = userService;
            this._ltDictionaryClient = ltDictionaryClient;
        }

        /// <summary>
        /// 获取用户拥有的项目
        /// </summary>
        /// <param name=""></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetUserProjects([FromQuery] GetUserProjectsClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            //获取当前用户拥有的项目权限
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                var result = new CommonResult();
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }
            return Ok(getDictionaryItemProjectsResult);
        }

        /// <summary>
        /// 获取项目角色分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetProjectRolePageList([FromQuery] GetProjectRolePageListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult<PageModel<GetProjectRolePageListClientOutPut>>();

            long count = 0;

            var condition = "";

            Dictionary<string, object> obj = new Dictionary<string, object>();

            //获取当前用户拥有的项目权限
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }

            if (!string.IsNullOrEmpty(input.Project))
            {
                if (!getDictionaryItemProjectsResult.Result.Any(p => p == input.Project))
                {
                    result.IsError = false;
                    result.Message = "获取成功";
                    result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                    result.Result = new PageModel<GetProjectRolePageListClientOutPut>
                    {
                        Data = new List<GetProjectRolePageListClientOutPut>(),
                        DataCount = 0,
                        Page = input.Page,
                        PageCount = 0,
                        PageSize = input.PageSize,
                    };
                }

                if (string.IsNullOrEmpty(condition))
                {
                    condition = $" \"Id\" In (Select \"RoleId\" From \"RoleProjectRelation\" Where \"Project\" = @project )";
                }
                else
                {
                    condition = $" And \"Id\" In (Select \"RoleId\" From \"RoleProjectRelation\" Where \"Project\" = @project )";
                }
                obj.Add("project", $"{input.Project}");
            }
            else
            {
                result.IsError = false;
                result.Message = "获取成功";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
                result.Result = new PageModel<GetProjectRolePageListClientOutPut>
                {
                    Data = new List<GetProjectRolePageListClientOutPut>(),
                    DataCount = 0,
                    Page = input.Page,
                    PageCount = 0,
                    PageSize = input.PageSize,
                };

                return Ok(result);
            }

            var info = this._userService.GetRoles(input.Page, input.PageSize, condition, " \"CreateTime\" desc", out count, obj);

            var total_num = Math.Ceiling(count / (decimal)input.PageSize);


            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;
            result.Result = new PageModel<GetProjectRolePageListClientOutPut>
            {
                Data = info.Select(p => new GetProjectRolePageListClientOutPut
                {
                    Name = p.Name,
                    CreateTimeStr = p.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    Description = p.Description,
                    Id = p.Id,
                    UpdateTimeStr = p.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                }).ToList(),
                DataCount = count,
                Page = input.Page,
                PageCount = Convert.ToInt32(total_num),
                PageSize = input.PageSize,
            };

            return Ok(result);
        }

        /// <summary>
        /// 获取角色基础信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRole([FromQuery] GetRoleDetailClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            CommonResult<GetRoleDetailClientOutPut> result = new CommonResult<GetRoleDetailClientOutPut>();

            var role = this._userService.GetRole(input.RoleId);
            if (role == null)
            {
                result.IsError = true;
                result.Message = "角色不存在";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
            }

            //获取角色关联项目
            var roleProjects = this._userService.GetRoleProject(input.RoleId);
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }

            bool haveAuth = false;
            foreach (var roleProject in roleProjects)
            {
                foreach (var getProject in getDictionaryItemProjectsResult.Result)
                {
                    if (roleProject == getProject)
                    {
                        haveAuth = true;
                        break;
                    }
                }
                if (haveAuth)
                {
                    break;
                }
            }
            if (!haveAuth)
            {
                result.IsError = true;
                result.Message = "你无权操作";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }

            result.Result = new GetRoleDetailClientOutPut
            {
                Id = role.Id,
                Name = role.Name,
                ActionTrees = new List<ActionTree>(),
                CreateTimeStr = role.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                Description = role.Description,
                UpdateTimeStr =role.UpdateTime.ToString("yyyy-MM-dd HH:mm:ss")
            };

            result.IsError = false;
            result.Message = "获取成功";
            result.Value = RS.BaseModel.Enum.EnumBaseResult.OK;

            return Ok(result);
        }

        /// <summary>
        /// 获取角色用户分页列表
        /// </summary>
        /// <param name="input">输入信息</param>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult GetRoleUserPageList([FromQuery] GetRoleUserPageListClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult();
            var role = this._userService.GetRole(input.RoleId);
            if (role == null)
            {
                result.IsError = true;
                result.Message = "角色不存在";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
            }

            //获取角色关联项目
            var roleProjects = this._userService.GetRoleProject(input.RoleId);
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }

            bool haveAuth = false;
            foreach (var roleProject in roleProjects)
            {
                foreach (var getProject in getDictionaryItemProjectsResult.Result)
                {
                    if (roleProject == getProject)
                    {
                        haveAuth = true;
                        break;
                    }
                }
                if (haveAuth)
                {
                    break;
                }
            }
            if (!haveAuth)
            {
                result.IsError = true;
                result.Message = "你无权访问";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }

            var result2 = this._userService.GetRoleUserInfoList(input);
            //根据供应商处理手机号，身份证号
            foreach (var data in result2.Result.Data)
            {
                data.IdCardNo = "";
                if (!(data.EmployeeType == "7" || data.EmployeeType == "98" || data.EmployeeType == "99" || data.EmployeeType == "101"))
                {
                    data.Phone = "";
                }
            }

            return Ok(result2);
        }

        /// <summary>
        /// 添加角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult AddRoleUser([FromBody] AddRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult();

            //获取角色关联项目
            var roleProjects = this._userService.GetRoleProject(input.RoleId);
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }

            bool haveAuth = false;
            foreach (var roleProject in roleProjects)
            {
                foreach (var getProject in getDictionaryItemProjectsResult.Result)
                {
                    if (roleProject == getProject)
                    {
                        haveAuth = true;
                        break;
                    }
                }
                if (haveAuth)
                {
                    break;
                }
            }
            if (!haveAuth)
            {
                result.IsError = true;
                result.Message = "你无权操作";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }

            return Ok(this._userService.AddRoleUser(input));
        }

        /// <summary>
        /// 删除角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult DelRoleUser([FromBody] DelRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult();

            //获取角色关联项目
            var roleProjects = this._userService.GetRoleProject(input.RoleId);
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }

            bool haveAuth = false;
            foreach (var roleProject in roleProjects)
            {
                foreach (var getProject in getDictionaryItemProjectsResult.Result)
                {
                    if (roleProject == getProject)
                    {
                        haveAuth = true;
                        break;
                    }
                }
                if (haveAuth)
                {
                    break;
                }
            }
            if (!haveAuth)
            {
                result.IsError = true;
                result.Message = "你无权操作";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }

            return Ok(this._userService.DelRoleUser(input));
        }

        /// <summary>
        /// 导入角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpPost]
        public IActionResult ImportRoleUser([FromForm] ImportRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            return Ok(this._userService.ImportProjectRoleUser(input));
        }

        /// <summary>
        /// 导出角色用户
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult ExportRoleUser([FromQuery] ExportRoleUserClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = new CommonResult();

            //获取角色关联项目
            var roleProjects = this._userService.GetRoleProject(input.RoleId);
            var getDictionaryItemProjectsResult = _ltDictionaryClient.GetDictionaryItemProjects(new Lutos.Dictionary.Domain.Integrate.Input.GetDictionaryItemProjectsInput
            {
                UserId = input.Uid
            });
            if (getDictionaryItemProjectsResult == null || getDictionaryItemProjectsResult.IsError)
            {
                result.IsError = true;
                result.Value = RS.BaseModel.Enum.EnumBaseResult.SystemError;
                result.Message = "获取当前用户的项目管理权限失败";
                return Ok(result);
            }

            bool haveAuth = false;
            foreach (var roleProject in roleProjects)
            {
                foreach (var getProject in getDictionaryItemProjectsResult.Result)
                {
                    if (roleProject == getProject)
                    {
                        haveAuth = true;
                        break;
                    }
                }
                if (haveAuth)
                {
                    break;
                }
            }
            if (!haveAuth)
            {
                result.IsError = true;
                result.Message = "你无权访问";
                result.Value = RS.BaseModel.Enum.EnumBaseResult.NoRight;
                return Ok(result);
            }

            var result2 = _userService.ExportRoleUser(input);
            if (result2.IsError)
            {
                return Ok(new CommonResult { IsError = true, Message = result.Message, Value = result.Value });
            }
            else
            {
                return File(result2.Result.MemoryStream, "application/octet-stream", result2.Result.FileName);
            }
        }

        /// <summary>
        /// 下载角色用户模板
        /// </summary>
        /// <returns></returns>
        [ApiAuthCheckFilter]
        [HttpGet]
        public IActionResult DownloadRoleUserTemplate([FromQuery] DownloadRoleUserTemplateClientInput input)
        {
            var currentUser = _userService.GetUserInfoByUid(new GetUserInfoByUidInput { AppAccessToken = "", AppId = "", Id = "", Uid = input.Uid }).Result;
            if (!currentUser.Actions.Where(p => p.ControlName != null).Any(p => p.ControlName.ToLower().Contains("projectuser")))
            {
                return Ok(new CommonResult
                {
                    IsError = true,
                    Message = "你无权操作",
                    Value = RS.BaseModel.Enum.EnumBaseResult.NoRight
                });
            }

            var result = _userService.DownloadRoleUserTemplate(input);
            if (result.IsError)
            {
                return Ok(new CommonResult { IsError = true, Message = result.Message, Value = result.Value });
            }
            else
            {
                return File(result.Result.MemoryStream, "application/octet-stream", result.Result.FileName);
            }
        }
    }
}
